#include "aux_idmanager.h"
#include "aux_thread.h"

typedef struct {
    pthread_mutex_t tLock;
    u32             nIdUsed;
    u8              byInited;
} TxIPCId;

static TxIPCId s_id;

EErrNo xIPCIdManagerGetId(u32 *pnId)
{
    if (!pnId)
        return -ERRNO_EPARAMETER_INVALID;

    if (!(s_id.byInited))
        return -ERRNO_ENOTINITIALIZED;

    if (pthread_mutex_lock(&(s_id.tLock)))
        return -ERRNO_ELOCK_FAIL;

    *pnId = ++(s_id.nIdUsed);

    pthread_mutex_unlock(&(s_id.tLock));

    return ERRNO_SUCCESS;
}

/* id manager is owned by the framework of xIPC */
EErrNo xIPCComponentIdManagerInit(void)
{
    if (s_id.byInited)
        return ERRNO_SUCCESS;

    s_id.byInited = 1;
    if (pthread_mutex_init(&(s_id.tLock), NULL))
    {
        s_id.byInited = 0;
        return ERRNO_FAIL;
    }

    s_id.nIdUsed = 0;
    return ERRNO_SUCCESS;
}

EErrNo xIPCComponentIdManagerDeinit(void)
{
    if (!(s_id.byInited))
        return ERRNO_SUCCESS;

    s_id.byInited = 0;
    pthread_mutex_destroy(&(s_id.tLock));
    return ERRNO_SUCCESS;
}
